//
//  SearchViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/12.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "SearchViewController.h"

#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "HeaderFileForEasyToTesco.h"

@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>{
    BOOL searchBool;
    NSString *sortStr;
    NSArray *titleArr;
    UIView *tempheaderview;
}

@property (nonatomic, strong)UITableView *searchTableview;
@property (nonatomic, strong)NSMutableArray *saveSearchArray;


@property (nonatomic, strong)NSMutableArray *searchArray;

@property (nonatomic, strong)UITextField *searchText;


@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self addsearchinitUI];
    
    [self addsearchtopView];
    
    [self addsearchtableviewUI];
    
    
    
}


- (void)addsearchinitUI {
    searchBool = YES;
    sortStr = @"价格最高";
    titleArr = @[@"价格最高", @"价格最低", @"最新发布", @"人气最高"];
    self.searchArray = [@[]mutableCopy];
    self.saveSearchArray = [@[]mutableCopy];
    
}

- (void)addsearchtopView {
    
    self.secondView.userInteractionEnabled = YES;
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    self.titleLabel.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    
    self.searchText = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(goBackBtn.frame), 5, WEITH-CGRectGetHeight(self.secondView.frame)*2, CGRectGetHeight(self.secondView.frame) - 10)];
    self.searchText.delegate = self;
    self.searchText.clearButtonMode = UITextFieldViewModeAlways;
    self.searchText.placeholder = @"请输入搜索内容";
    self.searchText.backgroundColor = [UIColor whiteColor];
    self.searchText.layer.cornerRadius = CGRectGetHeight(self.searchText.frame)/2;
    self.searchText.layer.masksToBounds = YES;
    self.searchText.returnKeyType = UIReturnKeyDone;
    [self setLeftViewWithTextField:self.searchText imageName:@"search-gray-icon.png"];
    [self.secondView addSubview:self.searchText];
    
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(WEITH-self.secondView.frame.size.height, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnclick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:searchBtn];
    
}

- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//搜索
- (void)searchBtnclick {
    [self.searchText resignFirstResponder];
    [self saveSearchdataToLocal:self.searchText.text];
    
    [tempheaderview removeFromSuperview];
    searchBool = NO;
    [self addheadersubview];
    [self searchdatasources];
}

- (void)addsearchtableviewUI {
    
    [self addheaderviewTitleView];
    self.searchTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1+30, WEITH, HIGHT*0.9-30) style:UITableViewStylePlain];
    self.searchTableview.dataSource= self;
    self.searchTableview.delegate = self;
    self.searchTableview.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.searchTableview];
}

- (void)addheaderviewTitleView {
    tempheaderview = [[UIView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, 30)];
    tempheaderview.userInteractionEnabled = YES;
    tempheaderview.backgroundColor = [UIColor yellowColor];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    titleLabel.text = @"搜索历史";
    [tempheaderview addSubview:titleLabel];
    [self.view addSubview:tempheaderview];
}


#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (searchBool == YES) {
        if ([[self readdataFromfile] count]!=0) {
            return [[self readdataFromfile] count]+1;
        } else {
            return 1;
        }
    } else {
        if (self.searchArray.count!=0) {
            return self.searchArray.count;
        } else {
            return 1;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (searchBool == YES) {
        static NSString *identifier = @"SearchCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if ([[self readdataFromfile] count] == 0) {
            cell.textLabel.text = @"暂无搜索记录";
        } else {
            if (indexPath.row == [[self readdataFromfile] count]) {
                cell.textLabel.textColor = [UIColor greenColor];
                cell.textLabel.text = @"清除搜索历史";
            } else {
            cell.textLabel.text = [NSString stringWithFormat:@"%@", [[self readdataFromfile] objectAtIndex:indexPath.row]];
            }
        }
        return cell;
    } else {
        //替换成自定义的cell
        static NSString *identifier = @"SearchCell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (self.searchArray.count == 0) {
            cell.textLabel.text = @"暂无";
        } else {
            cell.textLabel.text = [NSString stringWithFormat:@"%@", self.searchArray[indexPath.row]];
        }
        
        return cell;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        return 35;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerview = [[UIView alloc] init];
    
    return headerview;
}

- (void)addheadersubview {
    tempheaderview = [[UIView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, 30)];
    tempheaderview.userInteractionEnabled = YES;
    tempheaderview.backgroundColor = [UIColor yellowColor];

    for (NSInteger i=0; i<titleArr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake((WEITH/4)*i, 0, WEITH/4, 30);
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(headerBtnclick:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        if (i == 0) {
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        }else {
             [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        button.tag = 540+i;
        [tempheaderview addSubview:button];
    }
    [self.view addSubview:tempheaderview];

}
- (void)headerBtnclick:(UIButton *)button {
    NSLog(@"%ld", button.tag);
    
    for (UIButton *tempBtn in button.superview.subviews) {
        if (tempBtn.tag == button.tag) {
            [tempBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        } else {
            [tempBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
    sortStr = titleArr[button.tag - 540];
    [self searchdatasources];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    return footview;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (searchBool == YES) {
        if (indexPath.row == [[self readdataFromfile] count]) {
            //清除搜索记录
            [self cleansaveData];
        } else {
            self.searchText.text = [NSString stringWithFormat:@"%@", [[self readdataFromfile] objectAtIndex:indexPath.row]];
        }
    }
}


- (void)searchdatasources {
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *search_text = self.searchText.text;
    NSString *city = @"丽水";
    NSString *county = @"遂昌县";
    NSString *sort = sortStr;
    
    NSDictionary *param = @{@"search_text":[NSString stringWithFormat:@"%@", search_text], @"city":[NSString stringWithFormat:@"%@", city], @"county":[NSString stringWithFormat:@"%@", county], @"sort":[NSString stringWithFormat:@"%@", sort]};
    
    [mgr POST:@"http://www.ylgw8.com/AppSearch/Search" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        [self.searchTableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
//         NSLog(@"数据请求错误原因:%@", error);
//         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//存储数据到本地
- (void)saveSearchdataToLocal:(NSString *)tempStr{
    
    self.saveSearchArray = [NSMutableArray arrayWithArray:[self readdataFromfile]];
    
    //1. 创建一个plist文件
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *filename=[path stringByAppendingPathComponent:@"searchdata.plist"];
    //创建
    NSFileManager* fm = [NSFileManager defaultManager];
    [fm createFileAtPath:filename contents:nil attributes:nil];
    
    //NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    //创建一个dic，写到plist文件里
//    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:@"sina",@"1",@"163",@"2",nil];
//    [dic writeToFile:filename atomically:YES];
    //创建一个nsarray,写到plist文件中,,判断是不是一样,不一致的时候才写入
    if (self.saveSearchArray.count!=0) {
        for (NSString *saveStr in self.saveSearchArray) {
            if (![saveStr isEqualToString:tempStr]) {
                [self.saveSearchArray addObject:[NSString stringWithFormat:@"%@", tempStr]];
                [self.saveSearchArray writeToFile:filename atomically:YES];
            }
        }
    }else {
        [self.saveSearchArray addObject:[NSString stringWithFormat:@"%@", tempStr]];
        [self.saveSearchArray writeToFile:filename atomically:YES];
    }

    [self.searchTableview reloadData];
    
//    NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];
//    NSLog(@"dic is:%@",dic2);
}

//清除历史记录数据
- (void)cleansaveData {
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *filename=[path stringByAppendingPathComponent:@"searchdata.plist"];
    NSMutableArray *ttarray = [@[]mutableCopy];
     [ttarray writeToFile:filename atomically:YES];
    
    [self.searchTableview reloadData];
    
}

//读取本地数据
- (NSMutableArray *)readdataFromfile{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths objectAtIndex:0];

    //获取一个plist文件
   NSString *filename=[path stringByAppendingPathComponent:@"searchdata.plist"];
    //读文件
    NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:filename];

    return arr;
    
}


/**
 *  给UITextField设置右侧的图片
 *
 *  @param textField UITextField
 *  @param imageName 图片名称
 */

-(void)setLeftViewWithTextField:(UITextField *)textField imageName:(NSString *)imageName{
    
    UIImageView *rightView = [[UIImageView alloc]init];
    
    rightView.image = [UIImage imageNamed:imageName];
    rightView.frame = CGRectMake(0, 0, CGRectGetHeight(textField.frame), CGRectGetHeight(textField.frame));
    rightView.contentMode = UIViewContentModeCenter;
    textField.leftView = rightView;
    textField.leftViewMode = UITextFieldViewModeAlways;
}
#pragma mark -- UITextFieldDelegate
//触摸空白处回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.searchText resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (textField.text.length == 0) {
        searchBool = YES;
        [tempheaderview removeFromSuperview];
        [self addheaderviewTitleView];
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您输入的内容为空,请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    }else {
        
        //存入数据到本地
        [self saveSearchdataToLocal:textField.text];
        
        searchBool = NO;
       
        [tempheaderview removeFromSuperview];
        
        [self addheadersubview];
        [self searchdatasources];
        
    }
    [self.searchTableview reloadData];
    return YES;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
